#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Calculator.hpp"
#include "Daemon.hpp"
#include <functional>
#include <memory>

using cal_func = std::function<Response(const Request &req)>;

class Prase
{
public:
    Prase(cal_func c):_cal(c)
    {}
    std::string Entry(std::string &package)
    {
        std::string message;
        std::string respstr;
        while(Decode(package, &message))
        {
            LOG(LogLevel::DEBUG)<<'\n'<<message;
            if(message.empty())    
                break;

            // 反序列化
            Request req;
            if (!req.Deserialize(message))
                break;
    
            // 计算
            Response resp = _cal(req);
    
            // 序列化
            std::string res;
            resp.Serialize(res);
            LOG(LogLevel::DEBUG)<<"\n"<<res;

    
            // 添加长度报头字段
            Encode(res);
    
            // 拼接应答
            respstr += res;
        }

        return respstr;
    }

private:
    cal_func _cal;
};

int main()
{
    LogModule::ENABLE_FILE_LOG();

    Daemon(false, false);

    //1计算模块
    Calculator mycal;
    Prase myparse([&mycal](const Request &req){
        return mycal.Excute(req);
    });

    std::unique_ptr<TcpServer> ts = std::make_unique<TcpServer>([&myparse](std::string& package){
        return myparse.Entry(package);
    });

    ts->InitServer();
    ts->Start();
    return 0;
}